﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace simFileWatch
{
    //声明一委托
    public delegate void FileWatchEventHandler(object sender, EventArgs e);
    public class FileWatcher
    {
        //声明事件,事件类型为所定义的委托
        public event FileWatchEventHandler FileWatchEvent;
        private bool _bLastStatus = false;  //记录所监控文件的状态

        //触发事件
        protected virtual void OnFileChange(EventArgs e)
        {
            if (FileWatchEvent != null)
            {
                FileWatchEvent(this, e);
            }
        }

        public void MonitorFile()
        {
            bool bCurrentStatus;

            //for ever
            while (true)
            {
                bCurrentStatus = File.Exists("test.txt");
                if (bCurrentStatus != _bLastStatus) //_bLastStatus为私有字段，初始值为false;
                {
                    _bLastStatus = bCurrentStatus;
                    OnFileChange(EventArgs.Empty);  //状态不符，说明文件被删除或重新创建，此时触发事件；
                }

            }
        }
    }
}
